<template>
	<el-dialog v-model="dialogVisible" :title="isAdd ? '添加商品' : '编辑商品'" width="79%" :before-close="handleClose"
		:destroy-on-close="true">
		<div style="font-size: 14px; line-height: 30px">
			<el-form :model="form" label-width="150px" :rules="rules" ref="formRef">
				<el-form-item label="商品名称：" prop="name">
					<el-input v-model="form.name" placeholder="输入商品名称"></el-input>
				</el-form-item>
				<el-form-item label="商品类目：" prop="categoryId">
					<el-select v-model="form.categoryId" class="m-2" placeholder="请选择商品类目" size="large" filterable
						style="width: 100%">
						<el-option v-for="item in categorys" :key="item.id" :label="item.categoryName"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="服务标签：" prop="serviceList">
					<div style="display: flex; flex-direction: column">
						<el-button type="primary" style="width: 100px" @click="openSelectLabel">选择标签</el-button>

						<div style="display: flex; margin-top: 10px; align-items: center" v-show="labelList.length">
							已选：
							<!-- backgroundColor: ' rgba($color: ' + scope.row.colorCode + ', $alpha: 0.5)', -->
							<div v-for="(item, index) in labelList" :key="index" :style="{
								color: item.colorCode,
								borderRadius: '5px',
								fontSize: '10px',
								display: 'flex',
								height: '25px',
								alignItems: 'center',
								paddingLeft: '8px',
								paddingRight: '8px',
								marginRight: '10px',
								backgroundColor: colorHextoRGB(item.colorCode),
							}">
								{{ item.name }}
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="权重：" prop="weight">
					<el-input v-model="form.weight" placeholder="权重越小越靠前"></el-input>
					<el-text style="font-size: 12px" type="danger">* 权重越小越靠前</el-text>
				</el-form-item>
				<el-form-item label="运费模板：" prop="freightId">
					<el-select v-model="form.freightId" class="m-2" placeholder="请选择运费模版" size="large" filterable
						style="width: 100%">
						<el-option v-for="item in freights" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="供货商：" prop="recommendation">
					<el-select v-model="form.supplierId" placeholder="请选择供货商" class="m-2" size="large" filterable
						style="width: 100%">
						<el-option :label="item.name" :value="item.id" v-for="item in supplierList"
							:key="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品推荐语：" prop="recommendation">
					<el-input type="textarea" v-model="form.recommendation" placeholder="输入商品推荐语"></el-input>
				</el-form-item>

				<el-form-item label="销量起始值：" prop="sales">
					<el-input-number type="textarea" v-model.number="form.sales"></el-input-number>
				</el-form-item>

				<el-form-item label="商品主图列表：" prop="mainImageList">
					<el-upload :headers="uploadHeader" v-model:file-list="mainImageListShow" :action="uploadUrl"
						:data="{ fileCode: 'GOODS' }" :on-preview="handlePictureCardPreview" list-type="picture-card"
						:on-success="handleMainSuccess" multiple>
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="商品详情图列表：" prop="infoImageList">
					<el-upload :headers="uploadHeader" v-model:file-list="infoImageListShow" :action="uploadUrl"
						:on-preview="handlePictureCardPreview" :data="{ fileCode: 'GOODS' }" list-type="picture-card"
						multiple :on-success="handleInfoSuccess">
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<skuTable :tableData="form.skuList" @getskuList="skuList"></skuTable>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="submit">提交</el-button>
				<el-button @click="handleClose">关闭</el-button>
			</span>
		</template>

		<selectLabel :selectedList="labelList" @tagSubmit="getTags" :dialogVisible="selectLabelVisible"
			@handleClose="labelHandleClose"></selectLabel>

		<el-dialog v-model="imgdialogVisible">
			<el-image w-full :src="dialogImageUrl" alt="Preview Image" fit="cover" />
		</el-dialog>
	</el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, watch, onBeforeMount, reactive } from 'vue';
import { getLabel, getCategory, freightList, addGoodsInfo, getGoodsInfo, getSupplier } from '/@/api/api';
import selectLabel from './selectLabel.vue';
import skuTable from '../skuTable.vue';
import { Session } from '/@/utils/storage';
import { colorHextoRGB } from '/@/utils/utils';
const uploadUrl = ref(import.meta.env.VITE_API_URL + 'common/upload');
import type { UploadProps } from 'element-plus';

const imgdialogVisible = ref(false);
const dialogImageUrl = ref('');
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
	dialogImageUrl.value = uploadFile.url!;
	imgdialogVisible.value = true;
};

const form = ref({
	mainImageList: [],
	infoImageList: [],
	sales: 0,
});
const categorys = ref([]);
const freights = ref([]);
const formRef = ref();

const mainImageListShow = ref([]);
const infoImageListShow = ref([]);

const selectLabelVisible = ref(false);
//显示在页面上的标签数组
const labelList = ref([]);

const loading = ref(false);
const props = defineProps({
	// 列表内容
	dialogVisible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => { },
	},
	isAdd: {
		type: Boolean,
		default: () => true,
	},
});

const rules = reactive({
	name: [{ required: true, message: '请输入商品名字', trigger: 'blur' }],
	categoryId: [{ required: true, message: '请选择商品类目', trigger: 'blur' }],
	serviceList: [{ required: true, message: '请选择服务标签', trigger: 'blur' }],
	weight: [{ required: true, message: '请输入权重', trigger: 'blur' }],
	freightId: [{ required: true, message: '请选择运费模板', trigger: 'blur' }],
	recommendation: [{ required: true, message: '请填写商品推荐语', trigger: 'blur' }],
	sales: [
		{ required: true, message: '请输入大于等于0的正整数', trigger: 'blur' },
		{ pattern: /^\+?[0-9]\d*$/, message: '请输入大于等于0的正整数' },
	],

	// mainImageList: [{ required: true, message: '请上传商品主图', trigger: 'blur' }],
	// infoImageList: [{ required: true, message: '请上传商品详情图', trigger: 'blur' }],
});

const dialogVisible = ref(false);

const uploadHeader = ref({
	'auth-token': `${Session.get('token')}`,
	'Cache-Control': 'no-cache',
});

watch(
	() => props.dialogVisible,
	async (val) => {
		dialogVisible.value = val;
		if (val) {
			if (!props.isAdd) {
				const { code, data } = await getGoodsInfo({ id: props.row.id });
				if (code === 200) {
					form.value = {
						...data.info,
						serviceList: data.info.serviceIdList,
					};
					mainImageListShow.value = [];
					data.info.mainImageList.forEach((item) => {
						mainImageListShow.value.push({
							url: item,
							response: {
								data: {
									fileUrl: item,
								},
							},
						});
					});
					infoImageListShow.value = [];
					data.info.infoImageList.forEach((item) => {
						infoImageListShow.value.push({
							url: item,
							response: {
								data: {
									fileUrl: item,
								},
							},
						});
					});
					makeLabels();
				}
				category();
			}
			getSupplierList();
		}
	}
);

//获取所有标签
async function makeLabels() {
	let { code, data } = await getLabel({});
	if (code == 200) {
		labelList.value = [];
		data.list.forEach((dataItem) => {
			form.value.serviceIdList = form.value.serviceList;
			if (form.value.serviceIdList.includes(String(dataItem.id)) || form.value.serviceIdList.includes(dataItem.id)) {
				labelList.value.push(dataItem);
			}

			// console.log('zzxcvzxcvzxcv', labelList.value)
		});
	}
}

const handleMainSuccess = (res) => {
	if (res.code == 200) {
		if (!form.value.mainImageList) {
			form.value.mainImageList = [];
		}
		// form.value.mainImageList.push(res.data.fileUrl.replace('blob:', ''));
	} else {
		ElMessage.error(res.msg);
	}
};

// handleInfoSuccess
const handleInfoSuccess = (res) => {
	if (res.code == 200) {
		if (!form.value.infoImageList) {
			form.value.infoImageList = [];
		}
		// form.value.infoImageList.push(res.data.fileUrl.replace('blob:', ''));
	} else {
		ElMessage.error(res.msg);
	}
};

onBeforeMount(() => {
	category();
	getFreightList();
	getSupplierList();
});
const supplierList = ref([]);
// 获取供货商列表
async function getSupplierList() {
	let { data } = await getSupplier({
		page: 1,
		size: 9999,
	});
	supplierList.value = data.list;
}

function getTags(val) {
	selectLabelVisible.value = false;
	form.value.serviceList = val.map((ele) => {
		return ele.id;
	});
	makeLabels();
}

// 获取商品分类
async function category() {
	const { code, data } = await getCategory({
		page: 1,
		size: 9999,
		parentId: 0,
	});
	if (code === 200) {
		categorys.value = data.list;
	}
}

// 获取运费模板
async function getFreightList() {
	const { code, data } = await freightList({ page: 1, size: 9999 });
	if (code === 200) {
		freights.value = data.list;
	}
}

// 打开服务标签
function openSelectLabel() {
	selectLabelVisible.value = true;
}

// 获取 sku 列表
function skuList(val) {
	form.value.skuListAdd = val.skuListAdd;
	form.value.skuListEdit = val.skuListEdit;
	form.value.skuListDel = val.skuListDelete;
}

// 添加商品
function submit() {
	console.log('🚀 ~ formRef.value.validate ~ 	form.value:', form.value);

	if (formRef?.value?.validate) {
		formRef.value.validate(async (valid, fields) => {
			if (valid) {
				form.value.mainImageList = [];

				mainImageListShow.value.forEach((item, index) => {
					form.value.mainImageList.push(item.response.data.fileUrl.replace('blob:', ''));
				});
				form.value.infoImageList = [];
				infoImageListShow.value.forEach((item, index) => {
					form.value.infoImageList.push(item.response.data.fileUrl.replace('blob:', ''));
				});

				let par = {
					...form.value,
				};
				delete par.skuList;
				const { code } = await addGoodsInfo(par);
				if (code === 200) {
					ElMessage.success('添加成功');
					form.value.skuListAdd = [];
					form.value.skuListEdit = [];
					form.value.skuListDel = [];
					handleClose();
				}
			}
		});
	}

	// console.log('form', form.value);
	// let { code, data } = await addLabel({
	// 	...form.value,
	// });
	// if (code == 200) {
	// 	ElMessage.success('操作成功');
	// 	handleClose();
	// }
}

const emit = defineEmits(['handleClose']);

function handleClose() {
	form.value = {};
	labelList.value = []; // 清空已选标签
	formRef.value.resetFields();
	mainImageListShow.value = [];
	infoImageListShow.value = [];
	emit('handleClose');
}

function labelHandleClose() {
	selectLabelVisible.value = false;
}
</script>

<style>
.desc_label {
	width: 20px;
}
</style>
